package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.AddEmplyeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.UpdateEmplyeeDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.utils.MD5Util;
import com.sky.vo.EmployeeVO;
import com.sky.vo.EmpployeePageQueryVO;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        String passwordDB= employee.getPassword();
        String md5Password = MD5Util.md5(password);



        // TODO 后期需要进行md5加密，然后再进行比对
        //password.equals(employee.getPassword())
        if (!Objects.equals(passwordDB,md5Password)) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 增加员工
     *
     * */
    @Override
    public void insert(AddEmplyeeDTO addEmplyeeDTO) {
        //用户名不能重复
        Employee byUsername = employeeMapper.getByUsername(addEmplyeeDTO.getUsername());
        if(byUsername!=null){
            throw new BaseException("用户名重复");
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(addEmplyeeDTO,employee);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5Hex(PasswordConstant.DEFAULT_PASSWORD).toUpperCase());
        //  String token = request.getHeader(JwtClaimsConstant.TOKEN);
        // Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        // Long aLong = claims.get(JwtClaimsConstant.EMP_ID, Long.class);
        Long aLong = BaseContext.getCurrentId();
        employee.setCreateUser(aLong);
        employee.setUpdateUser(aLong);
        employeeMapper.insert(employee);
    }
    /**
     * 员工分页查寻
     * */

    @Override
    public PageResult<EmpployeePageQueryVO> page(EmployeePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<EmpployeePageQueryVO> page= employeeMapper.pageQuery(dto);
        return new PageResult<EmpployeePageQueryVO>(page.getTotal(),page.getResult());
    }

    @Override
    public void enableOrDisable(Long id, Integer status) {
        Employee employee=new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }
     /**
      * 修改回显
      * */
    @Override
    public EmployeeVO getById(Long id) {
        EmployeeVO employeeVO= employeeMapper.selectById(id);
        return employeeVO;
    }
    /**
     * 修改员工信息
     * */

    @Override
    public void update(UpdateEmplyeeDTO updateEmplyeeDTO) {
        Employee byUsername = employeeMapper.getByUsername(updateEmplyeeDTO.getUsername());
        if(byUsername==null){

        }else {
            if(Objects.equals(updateEmplyeeDTO.getId(),byUsername.getId())){

            }else {
                throw new BaseException("用户名不能重复");
            }
        }


        Employee employee = new Employee();
        BeanUtils.copyProperties(updateEmplyeeDTO,employee);
        employee.setSex(updateEmplyeeDTO.getSex()+"");
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);


    }

}
